package net.wanho.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import net.wanho.constant.UserConstant;
import net.wanho.dto.AssignRoleDTO;
import net.wanho.dto.UserInfoDTO;
import net.wanho.mapper.UserRoleMapper;
import net.wanho.po.UserInfo;
import net.wanho.po.UserRole;
import net.wanho.service.UserInfoService;
import net.wanho.mapper.UserInfoMapper;
import net.wanho.util.PageInfoUtil;
import net.wanho.vo.PageInfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2024-10-18 16:14:23
*/
@Service
@RequiredArgsConstructor
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{

    private final UserRoleMapper userRoleMapper;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public PageInfo<UserInfo> listPage(int pageNum, int pageSize, UserInfoDTO userInfoDTO) {
        Page<UserInfo> page = new Page<>(pageNum, pageSize);

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.like(!ObjectUtils.isEmpty(userInfoDTO.getUserCode()), "i.user_code", userInfoDTO.getUserCode());
        wrapper.eq(!ObjectUtils.isEmpty(userInfoDTO.getRoleId()),"r.role_id", userInfoDTO.getRoleId());
        wrapper.eq(!ObjectUtils.isEmpty(userInfoDTO.getUserState()), "i.user_state", userInfoDTO.getUserState());

        this.baseMapper.selectByPage(page, wrapper);

        PageInfo<UserInfo> pageInfo = PageInfoUtil.convert(page);

        // 获取创建人
        pageInfo.getResultList().forEach(item -> {
            item.setGetCode(this.getById(item.getCreateBy()).getUserCode());
        });

        return pageInfo;
    }

    @Override
    public void assignRole(AssignRoleDTO assignRoleDTO) {
        userRoleMapper.delete(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, assignRoleDTO.getUserId()));

        List<UserRole> list = assignRoleDTO.getRoleList().stream()
                .filter(role -> assignRoleDTO.getRoleCheckList().contains(role.getRoleName()))
                .map(role -> {
                    UserRole userRole = new UserRole();
                    userRole.setRoleId(role.getRoleId());
                    userRole.setUserId(assignRoleDTO.getUserId());
                    return userRole;
                })
                .collect(Collectors.toList());

        // 删除redis中旧的菜单数据
        redisTemplate.delete(UserConstant.MENU_PREFIX + assignRoleDTO.getUserId());

        userRoleMapper.insert(list);
    }
}




